//
//  KABillDetailVC.swift
//  kano
//
//  Created by Frank on 2024/9/18.
//

import Foundation
import JXSegmentedView

class KABillDetailVC:KABaseVC {
    
    lazy var headerView: KABillDetailHeader = {
        let view = KABillDetailHeader(frame: CGRect(x: 0, y: UIDevice.ka_fullNavHeight, width: var_screenWidth, height: kscale(184)))
        view.var_repayBtn.addTarget(self, action: #selector(ka_repayBtnClick(_:)), for: .touchUpInside)
        return view
    }()
    
    
    @objc func ka_repayBtnClick(_ sender: UIButton) {
        if sender.titleLabel?.text == "Repay now" {
            KAFlutterManager.showFlutterVC(route: "/repayment?loanGid=\(detailId)", parameter: [:])
            
//            navigationController?.pushViewController(KARepaymentDetails(with: detailId), animated: true)
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
    
    //JXSegmentedBaseDataSource
    lazy var segmentedDataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.isTitleColorGradientEnabled = true
        //dataSource.titles = ["Repayment", "Repayment is done"]
        dataSource.titleNormalColor = .black
        dataSource.titleSelectedColor = .themeColor
        return dataSource
    }()
    lazy var segmentedView: JXSegmentedView = {
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 20
        indicator.indicatorColor = .themeColor
        let segmentedView = JXSegmentedView()
        segmentedView.indicators = [indicator]
        segmentedView.dataSource = segmentedDataSource
        segmentedView.delegate = self
        segmentedView.frame = CGRect(x: kscale(12), y: headerView.bottom, width: view.bounds.width-kscale(24), height: kscale(50))
        segmentedView.backgroundColor = .white
        segmentedView.ka_addTopCorner(withRadius: kscale(16))
        return segmentedView
    }()
    lazy var listContainerView: JXSegmentedListContainerView! = {
        let container = JXSegmentedListContainerView(dataSource: self)
        container.frame = CGRectMake(kscale(12), segmentedView.bottom, var_screenWidth-kscale(24), UIDevice.ka_viewHeight-segmentedView.height-headerView.height)
        return container
    }()
    
    var model: KABillDetailModel?
    
    var detailId: String = ""
    
    init(with id: String) {
        super.init(nibName: nil, bundle: nil)
        detailId = id
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .colorf2f2f5
        
        ka_showCustomerNavBar(type: .normal)
        var_navBar.var_titleLabel.text = "Loan Bill Detail"
        
        
        view.addSubview(headerView)
        //        view.addSubview(segmentedView)
        //        segmentedView.listContainer = listContainerView
        //        view.addSubview(listContainerView)
        
        requestData()
    }
    func requestData() {
        view.showLoading()
        let paraDic:[String : Any] = [ "userGid":KAUserManager.shared.user.userGid, "loanGid": detailId ]
        billProvider.request(.billDetail(paraDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KABillDetailModel>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else { return }
                            model = content
                            headerView.model = model
                            //MARK: - Attention
                            //大额 或 蝌蚪贷
                            if model!.subLoanCount > 0 || model!.tadpoleLoanFlag {
                                segmentedDataSource.titles = ["Repayment", "Repayment is done"]
                            } 
                            //小额
                            else {
                                segmentedDataSource.titles = ["Repayment"]
                            }
                            view.addSubview(segmentedView)
                            segmentedView.listContainer = listContainerView
                            view.addSubview(listContainerView)
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    func requestRepayHistory() {
        view.showLoading()
        let paraDic:[String : Any] = [ "userGid":KAUserManager.shared.user.userGid,
                                       "loanGid": "",
                                       "currentPageIndex": 0,
                                       "paginationSize": 0]
        billProvider.request(.repayHistory(paraDic)) { result in
            self.view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else { return }
                            
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
}

extension KABillDetailVC: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        if let dotDataSource = segmentedDataSource as? JXSegmentedDotDataSource {
            //先更新数据源的数据
            dotDataSource.dotStates[index] = false
            //再调用reloadItem(at: index)
            segmentedView.reloadItem(at: index)
        }
        
        navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
    }
}

extension KABillDetailVC: JXSegmentedListContainerViewDataSource {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        if let titleDataSource = segmentedView.dataSource as? JXSegmentedBaseDataSource {
            return titleDataSource.dataSource.count
        }
        return 0
    }
    
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        //有分期数据是大额 || 蝌蚪贷
        if model!.subLoanCount > 0 || model!.tadpoleLoanFlag {
            if index == 0 {
                return KABillDetailPager(with: model!, isRepaidPage: false,loanGid: detailId)
            } else {
                return KABillDetailPager(with: model!, isRepaidPage: true,loanGid: detailId)
            }
        } else {
            return KABillDetailPager(with: model!, isRepaidPage: false,loanGid: detailId)
        }
    }
}

